const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors({
  origin: process.env.CORS_ORIGIN || '*',
  credentials: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));

// 静态文件服务（图片访问）
app.use('/uploads', express.static('uploads'));

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    environment: process.env.NODE_ENV
  });
});

// API路由
app.get('/api', (req, res) => {
  res.json({
    message: '微信公众号一键排版工具 API',
    version: '1.0.0',
    endpoints: {
      health: '/health',
      auth: '/api/auth/*',
      articles: '/api/articles/*',
      templates: '/api/templates/*',
      images: '/api/images/*'
    }
  });
});

// 挂载路由
const uploadRoutes = require('./routes/upload');
app.use('/api/upload', uploadRoutes);

// TODO: 待实现的路由
// app.use('/api/auth', require('./routes/auth'));
// app.use('/api/articles', require('./routes/articles'));
// app.use('/api/templates', require('./routes/templates'));

// 404处理
app.use((req, res) => {
  res.status(404).json({
    code: 404,
    message: 'API endpoint not found'
  });
});

// 错误处理
app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(500).json({
    code: 500,
    message: err.message || 'Internal server error'
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log('==============================================');
  console.log(`🚀 Server is running on port ${PORT}`);
  console.log(`📊 Health check: http://localhost:${PORT}/health`);
  console.log(`🔗 API docs: http://localhost:${PORT}/api`);
  console.log(`🌍 Environment: ${process.env.NODE_ENV || 'development'}`);
  console.log('==============================================');
});

module.exports = app;

